#include "plane.h"
#include "utils.h"
#include "forcewrapper.h"

Plane::Plane(b2World *world, b2Vec2 pos, float angle_in_radius, float density, float friction)
    : PolygonBody(world, b2_dynamicBody, planeVertices, sizeof(planeVertices) / sizeof(b2Vec2), pos, angle_in_radius, density, friction),
      engineForce(0, 0), forceId(-1)
{
}

void Plane::draw(QPainter *painter)
{
    painter->save();
    b2Vec2 position = body->GetPosition();
    painter->translate(position.x, position.y);
    painter->rotate(body->GetAngle() * 180 / M_PI);

    static const QLineF hotWinds[] = {
        QLineF(QPointF(2.3, 0.5), QPointF(2.9, 0.8)),
        QLineF(QPointF(2.3, 0), QPointF(3, 0)),
        QLineF(QPointF(2.3, -0.5), QPointF(2.9, -0.8))
    };

    if(forceId != -1) {
        float angle = getAngle();
        float horizonEngineForce = engineForce.x * cos(angle) + engineForce.y * sin(angle);
        float verticalEngineForce = engineForce.y * cos(angle) - engineForce.x * sin(angle);

        if(fabs(horizonEngineForce) < 1e-6) {

        } else if(horizonEngineForce < 0) {
            painter->drawLines(hotWinds, sizeof(hotWinds) / sizeof(QLineF));
        } else {
            painter->rotate(180);
            painter->drawLines(hotWinds, sizeof(hotWinds) / sizeof(QLineF));
            painter->rotate(-180);
        }

        if(fabs(verticalEngineForce) < 1e-6) {

        } else if(verticalEngineForce < 0) {
            painter->rotate(90);
            painter->drawLines(hotWinds, sizeof(hotWinds) / sizeof(QLineF));
            painter->rotate(-90);
        } else {
            painter->rotate(-90);
            painter->drawLines(hotWinds, sizeof(hotWinds) / sizeof(QLineF));
            painter->rotate(90);
        }
    }
    painter->restore();
    PolygonBody::draw(painter);
}

void Plane::step()
{
    PolygonBody::step();
}

void Plane::applyEngineForce(ForceWrapper *force)
{
    engineForce = force->getForce();
    if(forceId == -1) {
        forceId = applyForce(force);
    } else {
        forces[forceId]->updateForce(engineForce);
    }
}

const b2Vec2 Plane::planeVertices[20] = {
    b2Vec2(0.5,2),
    b2Vec2(-0.5,2),
    b2Vec2(-0.5,1.5),
    b2Vec2(-1.5,1.5),
    b2Vec2(-1.5,0.5),
    b2Vec2(-2,0.5),
    b2Vec2(-2,-0.5),
    b2Vec2(-1.5,-0.5),
    b2Vec2(-1.5,-1.5),
    b2Vec2(-0.5,-1.5),
    b2Vec2(-0.5,-2),
    b2Vec2(0.5,-2),
    b2Vec2(0.5,-1.5),
    b2Vec2(1.5,-1.5),
    b2Vec2(1.5,-0.5),
    b2Vec2(2,-0.5),
    b2Vec2(2,0.5),
    b2Vec2(1.5,0.5),
    b2Vec2(1.5,1.5),
    b2Vec2(0.5,1.5),
};
